<template>
	<view class="container">
	
		<view class="header">
			<image class="header-bg" src="/static/index_header-bg.png"  mode="aspectFill"></image>
			<view class="header-content">
				<view class="xiaoxi"><image src="/static/消息中心@2x.png" mode="aspectFit"></image></view>
				<view class="title">首页</view>
				<view class="location-bar">
					<view class="location">
						<image class="location-icon" src="/static/定位2@2x.png" @click="toSelectCity" mode="aspectFit"></image>
						<text>{{locationText}}</text>
					</view>
					<view class="refresh" @click="refreshLocation">
						<image class="refresh-icon" src="/static/刷新 (1)@2x.png" mode="aspectFit"></image>
						<text>刷新</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 四个功能按钮 -->
		<view class="function-grid">
			<view class="function-item" 
				v-for="(item, index) in functions" 
				:key="index"
				@click="handleFunctionClick(item)"
			>
				<image :src="item.icon" mode="aspectFit"></image>
				<text>{{item.name}}</text>
			</view>
		</view>

		<!-- 附近加油站 -->
		<view class="section">
			<view class="section-header">
				<text>附近加油站</text>
				<view class="more" @click="goToRefuel">
					更多
					<text class="more-icon">›</text>
				</view>
			</view>
			<view class="map-container">
				<map 
					class="map"
					:latitude="latitude"
					:longitude="longitude"
					:markers="markers"
					:scale="14"
					show-location
					:show-compass="true"
					:enable-rotate="true"
					:enable-overlooking="true"
					:enable-satellite="false"
					:enable-traffic="false"
					type="gcj02"
				></map>
			</view>
		</view>

		<!-- 优惠团购 -->
		<view class="section">
			<view class="section-header">
				<text>优惠团购</text>
				<view class="more" @click="goToGroupBuy">
					更多 >
				</view>
			</view>
			<view class="promotion-grid">
				<view 
					class="promotion-item" 
					v-for="(item, index) in promotions" 
					:key="index"
					@click="goToGroupBuyDetail(item)"
				>
					<image :src="item.image" mode="aspectFill"></image>
					<text>{{item.title}}</text>
				</view>
			</view>
		</view>

		<!-- 底部导航栏 -->
		<MagicNavigationBar 
			:items="items" 
			:digHolePosition="1" 
			:selectedColor="selectedColor"
			:color="color"
			@onTabSelect="onTabSelect" 
			:current="currentTab"
			:backgroundColor="backgroundColor"
			:screenBackgroundColor="screenBackgroundColor"
			:indicatorPadding="indicatorPadding"
			:indicatorSize="indicatorSize"
			:indicatorBackground="indicatorBackground"
		>
			<template v-slot:indicatorContent>
				<view class="indicator-content">
					<image @click="toRescue" :src="img" mode="aspectFit"></image>
				</view>
			</template>
		</MagicNavigationBar>
	</view>
</template>


<script>
import MagicNavigationBar from "@/uni_modules/jorbin-DigHoleNavigationBar/components/jorbin-DigHoleNavigationBar/jorbin-DigHoleNavigationBar.vue"
import amap from '@/utils/amap.js'
import locationService from '@/utils/location.js'

export default {
	components: {
		MagicNavigationBar
	},
	data() {
		return {
			cfuser: '',
			img: '/static/warning.png',
			selectedColor: '#2979ff',
			color: '#666666',
			currentTab: 0,
			backgroundColor: '#ffffff',
			screenBackgroundColor: '#f5f5f5',
			indicatorPadding: 8,
			indicatorSize: 75,
			indicatorBackground: '#ff8033',
			functions: [{
				icon: '/static/车辆维修1-01@2x.png',
				name: '车辆维修',
				path: '/packagesMap/vehicleMaintenance/vehicleMaintenance'
			}, {
				icon: '/static/保养@2x.png',
				name: '汽车保养'
			}, {
				icon: '/static/洗车@2x.png',
				name: '专业洗车'
			}, {
				icon: '/static/加油枪 (1)@2x.png',
				name: '就近加油',
				path: '/packagesMap/refuelNearby/refuelNearby'
			}],
			latitude: 35.234850,
			longitude: 113.248600,
			markers: [],
			promotions: [
				{
					id: '1',
					image: '/static/index_活动2.png',
					title: '汽车惠民活动走进计划共和国撒打算大',
					industry: '济源某某汽车行业',
					date: '2023/3/10 11:09',
					currentPrice: '99.00',
					originalPrice: '199.00',
					description: '哇喔！蹭羊毛的看过来！易车修汽车维修服务中心出优惠团购了！',
					endDate: '2023-3-10 08:00 至 2023-3-18 23:59',
					phone: '0379-66666666'
				},
				{
					id: '2',
					image: '/static/index_活动2.png',
					title: '汽车惠民活动走进大大撒啊但是啊撒打算大',
					industry: '济源某某汽车行业',
					date: '2023/3/10 11:09',
					currentPrice: '99.00',
					originalPrice: '199.00',
					description: '哇喔！蹭羊毛的看过来！易车修汽车维修服务中心出优惠团购了！',
					endDate: '2023-3-10 08:00 至 2023-3-18 23:59',
					phone: '0379-66666666'
				},
				{
					id: '3',
					image: '/static/index_活动2.png',
					title: '汽车惠民活动走进计划共和国撒打算大',
					industry: '济源某某汽车行业',
					date: '2023/3/10 11:09',
					currentPrice: '99.00',
					originalPrice: '199.00',
					description: '哇喔！蹭羊毛的看过来！易车修汽车维修服务中心出优惠团购了！',
					endDate: '2023-3-10 08:00 至 2023-3-18 23:59',
					phone: '0379-66666666'
				},
				{
					id: '4',
					image: '/static/index_活动2.png',
					title: '汽车惠民活动走进大大撒啊但是啊撒打算大',
					industry: '济源某某汽车行业',
					date: '2023/3/10 11:09',
					currentPrice: '99.00',
					originalPrice: '199.00',
					description: '哇喔！蹭羊毛的看过来！易车修汽车维修服务中心出优惠团购了！',
					endDate: '2023-3-10 08:00 至 2023-3-18 23:59',
					phone: '0379-66666666'
				}
			],
			items: [{
				icon: {
					src: '/static/index_line.png',
					width: 30,
					height: 30
				},
				text: '首页',
				selectedIcon: {
					src: '/static/index.png'
				},
				url: '/pages/index/index'
			}, {
				type: 'indicator',
				text: '上传',
				url: '/packagesRescue/rescue/rescue'
			}, {
				icon: {
					src: '/static/my_line.png',
					width: 30,
					height: 30
				},
				text: '我的',
				selectedIcon: {
					src: '/static/my.png'
				},
				url: '/pages/my/my'
			}],
			searchRadius: 5000,
			mapKey: 'CFUBZ-GRYCJ-IAJFO-DT56D-EUSBE-RTBGY',
			locationText: '定位中...',
			isRefreshing: false,
			gasStationConfig: {
				north: { distance: 0.001, name: '中国石化加油站(人民路站)' },
				east: { distance: 0.005, name: '中国石油加油站(塔南路站)' },
				south: { distance: 0.002, name: '壳牌加油站(山阳路站)' },
				west: { distance: 0.004, name: '中国石化加油站(太行路站)' }
			},
			markerStyle: {
				width: 15,
				height: 22,
				iconPath: '/static/位置 拷贝 4@2x.png',
			}
		}
	},
	onLoad() {
		// 获取当前登录的cfuser
		this.cfuser = uni.getStorageSync('cfuser')
		// 如果没有登录则跳转到登录页面
		console.log(this.cfuser)
		if (!this.cfuser) {
			uni.reLaunch({
				url: '/packagesLogin/login/login'
			})
			return
		}
		// 获取当前位置
		this.initLocation()
		this.getLocation()
		
		
	},
	methods: {
		toRescue() {
			uni.redirectTo({
				url: "/packagesRescue/rescue/rescue",
			})
		},
		onTabSelect(index, item) {
			uni.redirectTo({
				url: item.url,
			})
		},
		// 跳转到选择城市页面
		toSelectCity() {
			uni.navigateTo({
				url: '/packagesMap/selectcity/selectcity'
			})
		},
		async initLocation() {
			try {
				// 获取当前位置
				const location = await locationService.getCurrentLocation();
				this.latitude = location.latitude;
				this.longitude = location.longitude;
				
				// 获取地址信息
				const result = await amap.reverseGeocoder(location);
				this.locationText = result.result.address;
				
				// 搜索附近加油站
				await this.searchNearbyStations();
			} catch (error) {
				console.error('初始化位置失败:', error);
				uni.showToast({
					title: '定位失败',
					icon: 'none'
				});
				
				// 使用默认位置
				this.latitude = 35.234850;
				this.longitude = 113.248600;
				this.locationText = '定位失败，使用默认位置';
				
				// 仍然尝试搜索附近加油站
				await this.searchNearbyStations();
			}
		},
		async searchNearbyStations() {
			try {
				const results = await amap.searchNearby('加油站', {
					latitude: this.latitude,
					longitude: this.longitude
				}, 3000);

				this.stations = results.detail.pois.map(poi => ({
					id: poi.id,
					name: poi.name,
					address: poi.address,
					distance: poi.distance,
					latitude: poi.latitude,
					longitude: poi.longitude,
					photos: poi.photos,
					tel: poi.tel,
					businessHours: poi.business_hours,
					rating: poi.rating
				}));

				console.log('加油站数据:', this.stations);

				// 更新地图标记
				this.markers = [
					// 用户位置标记
					{
						id: 'user',
						latitude: this.latitude,
						longitude: this.longitude,
						iconPath: '/static/椭圆 3 拷贝 2@2x.png',
						width: 18,
						height: 28,
						anchor: { x: 0.5, y: 0.5 },
						zIndex: 99
					},
					// 加油站标记
					...this.stations.map(station => ({
						id: station.id,
						latitude: station.latitude,
						longitude: station.longitude,
						iconPath: '/static/位置 拷贝 4@2x.png',
						width: 15,
						height: 24
					}))
				];

				console.log('地图标记:', this.markers);

			} catch (error) {
				console.error('搜索加油站失败:', error);
				uni.showToast({
					title: '搜索加油站失败',
					icon: 'none'
				});
			}
		},
		refreshLocation() {
			this.initLocation();
		},
		handleFunctionClick(item) {
			if (!item.path) {
				uni.showToast({
					title: '功能开发中',
					icon: 'none'
				});
				return;
			}

			// 如果是车辆维修或加油站，需要传入位置信息
			if (item.path.includes('vehicleMaintenance') || item.path.includes('refuelNearby')) {
				uni.navigateTo({
					url: `${item.path}?latitude=${this.latitude}&longitude=${this.longitude}`
				});
			} else {
				uni.navigateTo({
					url: item.path
				});
			}
		},
		goToRefuel() {
			uni.navigateTo({
				url: '/packagesMap/refuelNearby/refuelNearby'
			})
		},
		goToGroupBuy() {
			uni.navigateTo({
				url: '/packagesMap/groupBuy/groupBuy'
			})
		},
		goToGroupBuyDetail(item) {
			// 将完整的活动数据通过 url 参数传递
			const params = encodeURIComponent(JSON.stringify(item))
			uni.navigateTo({
				url: `/packagesMap/groupBuyDetail/groupBuyDetail?params=${params}`
			})
		}
	},
	onReady() {
		this.initLocation();
	},
}
</script>

<style>
.xiaoxi image{
	width: 40rpx;
	height: 40rpx;
	margin-left: 20rpx;
	margin-bottom: -55rpx;
}
.container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

/* 顶部背景和标题 */
.header {
	position: relative;
	height: 420rpx;
	overflow: hidden;
}

.header-bg {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 0;
}

.header-content {
	position: relative;
	padding: 0;
	padding-top: 30rpx;
	z-index: 1;
}

.title {
	color: #fff;
	font-size: 36rpx;
	font-weight: 500;
	text-align: center;
	margin-bottom: 48rpx;
}

.location-bar {
	background: #fff;
	padding: 28rpx 32rpx;
	border-radius: 60rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 0 40rpx;
	box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.1);
}

.location {
	display: flex;
	align-items: center;
	flex: 1;
	cursor: pointer;  /* 添加手型光标 */
}

.location:active {
	opacity: 0.7;  /* 点击时的反馈效果 */
}

.location-icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 16rpx;
}

.location text {
	font-size: 28rpx;
	color: #333;
	flex: 1;
}

.refresh {
	display: flex;
	align-items: center;
	padding-left: 24rpx;
	border-left: 2rpx solid #eee;
	cursor: pointer;  /* 添加手型光标 */
}

.refresh:active {
	opacity: 0.7;  /* 点击时的反馈效果 */
}

.refresh-icon {
	width: 32rpx;
	height: 32rpx;
	margin-right: 8rpx;
}

.refresh text {
	font-size: 28rpx;
	color: #4B7BF9;
}

/* 功能按钮区域 */
.function-grid {
	margin: -80rpx 32rpx 32rpx;
	padding: 40rpx 20rpx;
	background: #fff;
	border-radius: 32rpx;
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 20rpx;
	position: relative;
	z-index: 2;
	box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.08);
}

.function-item {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.function-item image {
	width: 70rpx;
	height: 70rpx;
	padding: 20rpx;
	border-radius: 22rpx;
	box-sizing: content-box;
}

/* 为每个功能按钮添加渐变背景色 */
.function-item:nth-child(1) image {
	background: linear-gradient(135deg, #A3C1DA 0%, #4B7BF9 100%);  /* 车辆维修 - 浅蓝到深蓝 */
}

.function-item:nth-child(2) image {
	background: linear-gradient(135deg, #FFE5B4 0%, #FFA033 100%);  /* 汽车保养 - 浅橙到深橙 */
}

.function-item:nth-child(3) image {
	background: linear-gradient(135deg, #B2EAB8 0%, #4CD964 100%);  /* 专业洗车 - 浅绿到深绿 */
}

.function-item:nth-child(4) image {
	background: linear-gradient(135deg, #A6D1FF 0%, #73B4FF 100%);  /* 就近加油 - 浅蓝到深蓝 */
}

.function-item text {
	font-size: 24rpx;
	color: #333;
	margin-top: 8rpx;
}

/* 附近加油站 */
.section {
	margin: 32rpx;
	background: #fff;
	border-radius: 24rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.04);
}

.section-header {
	padding: 24rpx 32rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: none;
}

.section-header text {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.more {
	font-size: 24rpx;
	color: #999;
	display: flex;
	align-items: center;
}

.more-icon {
	margin-left: 8rpx;
	font-size: 28rpx;
	color: #999;
	line-height: 1;
}

.map-container {
	height: 360rpx;
	width: 100%;
	position: relative;
	padding: 0 20rpx 20rpx;
	box-sizing: border-box;
}

.map {
	width: 100%;
	height: 100%;
	border-radius: 16rpx;
	overflow: hidden;
}

/* 优惠团购 */
.promotion-grid {
	padding: 20rpx;
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 20rpx;
	margin-bottom: 200rpx;
}

.promotion-item {
	border-radius: 12rpx;
	overflow: hidden;
	background: #fff;
}

.promotion-item image {
	width: 100%;
	height: 240rpx;
	border-radius: 12rpx;
}

.promotion-item text {
	display: block;
	padding: 16rpx;
	font-size: 26rpx;
	color: #333;
	line-height: 1.4;
}

/* 底部导航栏样式调整 */
.indicator-content {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 100%;
}

.indicator-content image {
	width: 80rpx;
	height: 80rpx;
}
</style>